package org.rayworks.downloadutils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class DownloadService extends IntentService {
	
	public static final String DATA_TAG = "org.rayworks.downloadutils.data";

	public DownloadService() {
		super("DownloadService");
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();		
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		if(intent != null && intent.getStringExtra("url") != null){
			String url = intent.getStringExtra("url");
			URL netUrl = null;
			try {
				netUrl = new URL(url);
				URLConnection urlConn = netUrl.openConnection();
				urlConn.setConnectTimeout(7000);
				
				InputStream in = urlConn.getInputStream();
				byte[] bytesRead = read(in);
				if(bytesRead != null){
					Intent i = new Intent(DownloadReceiver.ACTION_TYPE);
					i.putExtra(DATA_TAG, bytesRead);
					sendBroadcast(i);
					System.out.println(">>> image data transit");
				}else{
					System.out.println(">>> image data load error...");
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (SocketTimeoutException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private byte[] read(InputStream in) {
		if(in != null){
			 ByteArrayOutputStream bos = new ByteArrayOutputStream();
			 BufferedInputStream bis = new BufferedInputStream(in);
			 byte[] body = new byte[1024];
			 int cntRead = 0;
			 try {
				while((cntRead = bis.read(body)) != -1){
					 bos.write(body, 0, cntRead);
				 }
				return bos.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}			 
		}
		return null;
	}
}
